package com.manor.im.utils

import android.content.Context
import android.database.Cursor
import android.provider.ContactsContract
import com.manor.common.ktx.toJson
import com.manor.common.utils.KLog
import com.manor.im.bean.PhoneBookBean
import com.manor.im.event.ContactSucEvent
import org.greenrobot.eventbus.EventBus

/**

 * @version 1.0

 * @date 2020/7/18  14:54
 */
object ContactsUtil {
    /**
     * 获取所有联系人
     *
     * @param context 上下文
     * @return 联系人集合
     */
    fun getContacts(context: Context, isNeedShow :Boolean = false): MutableList<PhoneBookBean> {
        val projection = arrayOf(
                ContactsContract.Contacts.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.NUMBER
        )
        val contacts: MutableList<PhoneBookBean> = mutableListOf()
        val currentTimeMillis = System.currentTimeMillis()
        //contacts.clear()
        var cursor: Cursor? = null
        val cr = context.contentResolver
        try {
            cursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null, "sort_key")
            if (cursor != null) {
                val displayNameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)
                val mobileNoIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
                var mobileNo: String?
                var displayName: String?
                while (cursor.moveToNext()) {
                    mobileNo = cursor.getString(mobileNoIndex).replace(" ".toRegex(),"")
                    displayName = cursor.getString(displayNameIndex)
                    contacts.add(PhoneBookBean(displayName, mobileNo))
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            if (cursor != null) {
                KLog.e("FriendLiveData-observer", "获取所有联系人耗时: " + (System.currentTimeMillis() - currentTimeMillis) + "，共计：" + cursor.count)
                KLog.e("FriendLiveData-observer", contacts.toJson())
                cursor.close()
            }
        }
        if (isNeedShow)
            EventBus.getDefault().post(ContactSucEvent(contacts))
        return contacts
    }
}